package cn.wen.javax.security;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.wen.java.lang.HelperOfReflect;
import cn.wen.javax.servlet.http.TokenOfWeb;
import cn.wen.javax.servlet.http.UtilsOfRequest;

/**
 * Title: 用户工厂（抽象）
 * <p>
 * Description:
 * <p>
 * Copyright: Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision：1.0 Date：2012/3/22 Description：初完成。
 *          <P>
 */
public abstract class AbstractUserFactory<T extends IUser> implements IUserFactory<T> {

    private final Logger log = Logger.getLogger(getClass());

    private Class<T> userClass;

    @Override
    public Class<T> getUserClass() {
	if (null == userClass) userClass = HelperOfReflect.getSuperClassGenricType(getClass());
	return userClass;
    }

    @Override
    public T newUser() {
	try {
	    return getUserClass().newInstance();
	}
	catch (Exception e) {
	    log.error("用户实例化失败！" + e.getMessage(), e);
	}
	return null;
    }

    @Override
    public T takeCurrentUser() {
	return takeCurrentUser(false);
    }

    @Override
    public T takeCurrentUser(boolean flag) {
	HttpSession session = UtilsOfRequest.getRequest().getSession();
	if (flag) { // 是否强制返回用户实体。
	    if (null == session) return newUser(); // 若未登录则创建一个未验证用户。
	}
	else {
	    if (null == session) return null;
	}
	T user = (T) session.getAttribute(TokenOfWeb.LOGGED_USER_TOKEN);
	if (flag && null == user) user = newUser();
	return user;
    }

    public T mapToUser(Map<String, ?> um) {
	T user = newUser();
	user.setLoginId((String) um.get("LOGIN_ID"));
	user.setPassword((String) um.get("PASSWORD"));
	user.setName((String) um.get("LOGIN_NAME"));
	user.setGender((String) um.get("GENDER"));
	user.setEmail((String) um.get("EMAIL"));
	user.setRegDate((Date) um.get("REG_DATE"));
	return user;
    }
}
